import { ref, nextTick } from 'vue'
import type { EditConfig, SaveAdapter } from '../index'

// 防重复提交的全局状态管理
class SaveManager {
  private pendingSaves = new Set<string>()
  private saveTimeouts = new Map<string, NodeJS.Timeout>()

  isPending(key: string): boolean {
    return this.pendingSaves.has(key)
  }

  addPending(key: string): void {
    this.pendingSaves.add(key)

    // 添加超时自动清理机制（30秒）
    if (this.saveTimeouts.has(key)) {
      clearTimeout(this.saveTimeouts.get(key)!)
    }

    const timeout = setTimeout(() => {
      this.removePending(key)
      console.warn(`[SaveManager] 自动清理超时的保存任务: ${key}`)
    }, 30000)

    this.saveTimeouts.set(key, timeout)
  }

  removePending(key: string): void {
    this.pendingSaves.delete(key)

    const timeout = this.saveTimeouts.get(key)
    if (timeout) {
      clearTimeout(timeout)
      this.saveTimeouts.delete(key)
    }
  }

  clear(): void {
    this.pendingSaves.clear()
    this.saveTimeouts.forEach((timeout) => clearTimeout(timeout))
    this.saveTimeouts.clear()
  }
}

const globalSaveManager = new SaveManager()

export function useEditHandler(
  editConfig: EditConfig,
  saveAdapter: SaveAdapter | null,
  emit: (event: string, ...args: any[]) => void
) {
  const beforeEditData = new Map<string, any>()
  const editingRows = new Set<string>()

  // 深度比较对象是否相等
  const deepEqual = (obj1: any, obj2: any): boolean => {
    if (obj1 === obj2) return true
    if (!obj1 || !obj2) return false
    if (typeof obj1 !== 'object' || typeof obj2 !== 'object') return false

    const keys1 = Object.keys(obj1)
    const keys2 = Object.keys(obj2)

    if (keys1.length !== keys2.length) return false

    for (const key of keys1) {
      if (!keys2.includes(key)) return false
      if (!deepEqual(obj1[key], obj2[key])) return false
    }

    return true
  }

  // 检测内容是否发生变化
  const hasChanged = (row: any, field?: string): boolean => {
    const key = getRowKey(row)
    const beforeData = beforeEditData.get(key)

    if (!beforeData) return true

    if (field) {
      return beforeData[field] !== row[field]
    }

    // 检查关键字段
    const fieldsToCheck = ['title', 'content', 'summary', 'level', 'content_type']
    return fieldsToCheck.some((fieldName) => beforeData[fieldName] !== row[fieldName])
  }

  // 获取行的唯一标识
  const getRowKey = (row: any): string => {
    return row.node_id || row.id || String(row)
  }

  // 开始编辑
  const startEdit = (row: any, field?: string): void => {
    const key = getRowKey(row)

    // 保存编辑前的数据
    if (!beforeEditData.has(key)) {
      beforeEditData.set(key, { ...row })
    }

    editingRows.add(key)
    emit('edit-activated', { row, field })
  }

  // 结束编辑
  const endEdit = async (row: any, field?: string, forced = false): Promise<void> => {
    const key = getRowKey(row)

    // 防重复提交检查
    if (globalSaveManager.isPending(key)) {
      console.log(`[EditHandler] 跳过重复保存: ${key}`)
      return
    }

    // 检查是否有变化
    const changed = forced || hasChanged(row, field)

    if (!changed) {
      // 没有变化，清理状态
      cleanup(key)
      emit('edit-closed', { row, field, changed: false })
      return
    }

    // 如果有保存适配器，执行保存
    if (saveAdapter?.editRow) {
      globalSaveManager.addPending(key)

      try {
        const result = await saveAdapter.editRow({ ...row })

        // 保存成功，更新数据
        if (result) {
          Object.assign(row, result)
        }

        emit('edit-closed', { row, field, changed: true, result })
        emit('save-success', { row, field, result })
      } catch (error) {
        console.error(`[EditHandler] 保存失败: ${key}`, error)
        emit('edit-closed', { row, field, changed: true, error })
        emit('save-error', { row, field, error })
      } finally {
        globalSaveManager.removePending(key)
        cleanup(key)
      }
    } else {
      // 没有保存适配器，仅触发事件
      emit('edit-closed', { row, field, changed: true })
      emit('row-edit', { row, field })
      cleanup(key)
    }
  }

  // 取消编辑
  const cancelEdit = (row: any): void => {
    const key = getRowKey(row)
    const beforeData = beforeEditData.get(key)

    if (beforeData) {
      // 恢复编辑前的数据
      Object.assign(row, beforeData)
    }

    cleanup(key)
    emit('edit-cancelled', { row })
  }

  // 清理编辑状态
  const cleanup = (key: string): void => {
    beforeEditData.delete(key)
    editingRows.delete(key)
  }

  // 检查行是否正在编辑
  const isEditing = (row: any): boolean => {
    const key = getRowKey(row)
    return editingRows.has(key)
  }

  // 批量保存所有编辑中的行
  const saveAll = async (): Promise<void> => {
    const promises: Promise<void>[] = []

    for (const key of editingRows) {
      const beforeData = beforeEditData.get(key)
      if (beforeData) {
        promises.push(endEdit(beforeData, undefined, true))
      }
    }

    await Promise.all(promises)
  }

  // 批量取消所有编辑
  const cancelAll = (): void => {
    for (const key of editingRows) {
      const beforeData = beforeEditData.get(key)
      if (beforeData) {
        cancelEdit(beforeData)
      }
    }
  }

  // 清理所有状态
  const clearAll = (): void => {
    beforeEditData.clear()
    editingRows.clear()
    globalSaveManager.clear()
  }

  return {
    startEdit,
    endEdit,
    cancelEdit,
    isEditing,
    hasChanged,
    saveAll,
    cancelAll,
    clearAll,
    getRowKey
  }
}
